﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using mBlogAPI.BL;
using mBlogAPI.Schema;
using mBlogAPI.Utils;
using System.Diagnostics;
using System.Collections.ObjectModel;
using MyDesktopMicroBlog;
using System.Windows.Threading;
using System.ComponentModel;

namespace MyDesktopMicroBlog.Tabs
{
    /// <summary>
    /// Interaction logic for BlogList.xaml
    /// </summary>
    public partial class BlogList : Page
    {
        enum UpdateMethod
        {
            Add,
            Insert
        }
        private RoutedEventHandler OpenUrlHandler;
        public ObservableCollection<Status> OStatusesCollection = new ObservableCollection<Status>();

        public BlogList()
        {
            InitializeComponent();
            lstBlogList.ItemsSource = OStatusesCollection;

            DispatcherTimer timer = new DispatcherTimer();
            double interval;
            if (!double.TryParse(Configurations.GetStatusUpdateFrequency(), out interval))
            {
                interval = 1;
            }
            timer.Interval = TimeSpan.FromSeconds(interval);
            //timer.IsEnabled = true;
            //timer.Tick += new EventHandler(timer_Tick);
            //timer.Start();

            timer_Tick(null, null);//call timer_Tick at first start up
        }

        void timer_Tick(object sender, EventArgs e)
        {
            NoArgDelegate statusFetcher = new NoArgDelegate(() =>
            {
                try
                {
                    Status[] tempStatuses = StatusesBL.GetFriendsStatuses().StatusList;
                    if (e == null)
                    {
                        UpdateStatusUI(tempStatuses, UpdateMethod.Add);
                    }
                    else
                    {
                        UpdateStatusUI(tempStatuses, UpdateMethod.Insert);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.LogError(ex);
                }
            });
            statusFetcher.BeginInvoke(null, null);
        }
        private void UpdateStatusUI(Status[] statusArray, UpdateMethod um)
        {
            try
            {
                this.Dispatcher.BeginInvoke(new OneArgDelegate<List<Status>>((target) =>
                {
                    target.ForEach(status =>
                    {
                        //int location =  OStatusesCollection.Find(s => s.Id == status.Id);
                        //if (location == -1)
                        //{
                            if (um == UpdateMethod.Insert)
                            {
                                OStatusesCollection.Insert(0, status);
                            }
                            else
                            {
                                OStatusesCollection.Add(status);
                            }
                        //}
                        //else
                        //{
                        //    ////rebind the status
                        //    OStatusesCollection[location].CreatedAt = status.CreatedAt;
                        //}
                    });
                }
                )
                , System.Windows.Threading.DispatcherPriority.SystemIdle
                , statusArray.ToList());

                if (um == UpdateMethod.Add)
                {
                    ShowMesssage("更新完成");
                }
            }
            catch (Exception ex)
            {
                if (um == UpdateMethod.Add)
                {
                    ShowMesssage("状态更新失败,请重试");
                }
                LogHelper.LogError(ex);
            }
        }

        private void ShowMesssage(string message)
        {
            this.Dispatcher.BeginInvoke(new NoArgDelegate(() =>
            {
                MessageHelper.ShowAndHideMessage(message);
            }));
        }

        private void ForwardStatusHandler(object sender, RoutedEventArgs e)
        {
            string statusID = ((Hyperlink)sender).CommandParameter.ToString();
            MessageBox.Show("要转发的状态ID：" + statusID);
        }

        private void ReplyStatusHandler(object sender, RoutedEventArgs e)
        {
            string IsOperateReply = ((Hyperlink)sender).CommandParameter.ToString();
            StatusManage statusWriter = new StatusManage();

            //operate orignal status
            if (IsOperateReply == "0")
            {
                statusWriter.StatusType = OperateStatusType.OrignalStatus;
            }
            else
            {
                statusWriter.StatusType = OperateStatusType.RepliedStatus;
            }

            ListBoxItem item = GetListBoxItemFromChild((sender as Hyperlink).Parent);
            statusWriter.Operation = "评论";
            statusWriter.Status = item.Content as Status;
            statusWriter.ShowDialog();
        }
        private void AddStatusToFavoritesHandler(object sender, RoutedEventArgs e)
        {
            string statusID = ((Hyperlink)sender).CommandParameter.ToString();
        }

        private void Image_MouseEnter(object sender, MouseEventArgs e)
        {
            popupUser.PlacementTarget = sender as UIElement;
            if (popupUser.IsOpen)
            {
                popupUser.IsOpen = false;
            }
            Image source = sender as Image;
            imgHead.Source = (sender as Image).Source;

            ListBoxItem item = GetListBoxItemFromChild(source as DependencyObject);
            User userInfo = (item.Content as Status).User;
            linkUserName.Inlines.Clear();
            linkUserName.Inlines.Add(new Run(userInfo.ScreenName));

            tbUserLocation.Text = userInfo.Location;
            tbUserDesc.Text = userInfo.Description;

            tbStatusCount.Text = userInfo.StatusesCount.ToString();
            tbFollowersCount.Text = userInfo.FollowersCount.ToString();
            tbFavouritesCount.Text = userInfo.FavouritesCount.ToString();

            linkUserName.CommandParameter = userInfo.Id;
            linkHeadPicture.CommandParameter = userInfo.Id;
            linkGotoUserPage.CommandParameter = userInfo.Id;

            if (OpenUrlHandler == null)
            {
                OpenUrlHandler = new RoutedEventHandler((o, args) =>
                {
                    Hyperlink link = o as Hyperlink;
                    OpenUserPage(link.CommandParameter.ToString());
                });

                linkUserName.Click += OpenUrlHandler;
                linkHeadPicture.Click += OpenUrlHandler;
                linkGotoUserPage.Click += OpenUrlHandler;
            }

            popupUser.IsOpen = true;
        }

        private void OpenUserPage(string userID)
        {
            try
            {
                Process.Start(Application.Current.Resources["UserBlogPrefix"] + userID);
            }
            catch
            {
            }
        }
        private ListBoxItem GetListBoxItemFromChild(DependencyObject d)
        {
            if (VisualTreeHelper.GetParent(d).GetType() == typeof(ListBoxItem))
            {
                return VisualTreeHelper.GetParent(d) as ListBoxItem;
            }
            else
            {
                return GetListBoxItemFromChild(VisualTreeHelper.GetParent(d));
            }
        }

        private void Image_MouseLeave(object sender, MouseEventArgs e)
        {
            if (!popupUser.IsMouseOver)
            {
                popupUser.IsOpen = false;
            }
        }

        private void btnGetMoreStatus_Click(object sender, RoutedEventArgs e)
        {
            MessageHelper.ShowMessage("正在获取更多...");
            NoArgDelegate statusFetcher = new NoArgDelegate(() =>
            {
                try
                {
                    Status[] tempStatuses = StatusesBL.GetMoreFriendsStatusesAndRecordCursorID().StatusList;
                    UpdateStatusUI(tempStatuses, UpdateMethod.Add);
                }
                catch (Exception ex)
                {
                    LogHelper.LogError(ex);
                    ShowMesssage("状态更新失败,服务器拒绝");
                }
            });
            statusFetcher.BeginInvoke(null, null);
        }

        private void lstBlogList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            OpenUserPage((sender as Hyperlink).CommandParameter.ToString());
        }
    }
}
